package ssh.dao;

import lombok.Setter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import ssh.entity.User;

import java.util.List;

public class UserDao {
    @Setter
    private SessionFactory sessionFactory;


    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }


    public void deleteById(Integer id) {
        String hql = "delete from User where id = :id";
        getSession().createQuery(hql).setParameter("id",id).executeUpdate();
    }

    public List<User> selectList() {
        String hql = "from User u left join fetch u.role";
        return getSession().createQuery(hql).list();
    }

    public void insert(User user) {
        if (user == null) {
            throw new IllegalArgumentException("User cannot be null");
        }
        getSession().save(user);
    }

    public User selectById(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }
        String hql = "FROM User u LEFT JOIN FETCH u.role WHERE u.id = :id";
        Query<User> query = getSession().createQuery(hql, User.class);
        query.setParameter("id", id);
        return query.uniqueResult();
    }

    public void update(User user) {
        if (user == null) {
            throw new IllegalArgumentException("User cannot be null");
        }
        if (user.getId() == null) {
            throw new IllegalArgumentException("User ID cannot be null for update");
        }
        getSession().update(user);
    }
}
